package com.example.good.controller;

import com.example.good.entity.Address;
import com.example.good.service.IAddressService;
import com.example.good.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("address")
@CrossOrigin(value = "http://localhost:8086")
public class AddressController extends BaseController{
    @Autowired
    private IAddressService addressService;
    @RequestMapping("add_new")
    public JsonResult<Integer> addNew(
            Address address,
            HttpSession session){
        Integer uid = getUidFromSession(session);
        String  username = getUsernameFromSession(session);
        Integer aid =  addressService.addNewAddress(uid, username, address);
        return new JsonResult<>(OK,aid);
    }
    @RequestMapping("get_by_uid")
    public JsonResult<List<Address>> getByUid(
            HttpSession session){
        Integer uid = getUidFromSession(session);
        List<Address> data = addressService.getByUid(uid);
        return new JsonResult<>(OK,data);
    }
    @RequestMapping("{aid}/set_default")
    public JsonResult<Void> setDefault(
            @PathVariable("aid") Integer aid,
            HttpSession session){
        Integer uid = getUidFromSession(session);
        String  username = getUsernameFromSession(session);
        addressService.setDefault(aid,uid,username);
        return new JsonResult<>(OK);
    }
    @RequestMapping("{aid}/delete")
    public JsonResult<Void> delete(
            @PathVariable("aid") Integer aid,
            HttpSession session){
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        addressService.delete(aid,uid,username);
        return new JsonResult<>(OK);
    }
    @RequestMapping("{aid}/add_modify")
    public JsonResult<Void> Add_modify(
            @PathVariable("aid") Integer aid,
            Address address,
            HttpSession session){
        Integer uid =getUidFromSession(session);
        String username = getUsernameFromSession(session);
        addressService.updateAddressByAid(aid,uid,username,address);
        return new JsonResult<>(OK);
    }
}
